/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.huawei.housekeeper.entity.MessageServiceEntity;
import com.huawei.housekeeper.entity.OrderMessageEntity;
import com.huawei.housekeeper.entity.TaskMessageEntity;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * 消息发送工具类
 *
 * @author y00464350
 * @since 2022-02-16
 */
@Component
public class MessageServiceUtil {

    private static final String EXCHANGE_NAME = "amq.topic";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     *
     * @param topic topic
     * @param message 消息
     * @throws JsonProcessingException json转换异常
     */
    public void sendMsgToMsgService(String topic, MessageServiceEntity message) throws JsonProcessingException {
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, topic, JsonUtil.objectToJson(message));
    }

    public void sendMsgToMsgService(String topic, OrderMessageEntity message) throws JsonProcessingException {
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, topic, JsonUtil.objectToJson(message));
    }

    public void sendMsgToMsgService(String topic, TaskMessageEntity message) throws JsonProcessingException {
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, topic, JsonUtil.objectToJson(message));
    }

    public <T> void sendMessageByAmqTopic(String topic, final T message, final String tenantDomain)
        throws JsonProcessingException {
        sendMessageByAmqTopic(topic, message, CommonUtil.buildHeaderMap(tenantDomain));
    }

    /**
     * mq发送消息要设置租户标识
     *
     * @param topic
     * @param message
     * @param headers
     * @param <T> message 泛型
     * @throws JsonProcessingException 数据处理异常
     */
    public <T> void sendMessageByAmqTopic(String topic, final T message, final Map<String, Object> headers)
        throws JsonProcessingException {
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, topic, JsonUtil.objectToJson(message), msg -> {
            if (CollectionUtils.isEmpty(headers)) {
                return msg;
            }
            headers.forEach((k, v) -> {
                msg.getMessageProperties().setHeader(k, v);
            });
            return msg;
        });
    }
}